<template>
  <div v-loading="loading" class="rc-cont">
    <template v-if="receivablesPlanIndex">
      <div v-if="!isSeas" class="rc-head">
        <el-button
          v-if="receivablesPlanSave"
          icon="el-icon-plus"
          @click="createClick('receivablesPlan')">
          {{ $t('crm.components.64edda19b1e39ea1f47b59950d114169') }}
        </el-button>
      </div>
      <el-table
        :data="palnList"
        :height="tableHeight"
        :cell-class-name="planCellClassName"
        stripe
        @row-click="handlePlanRowClick">
        <el-table-column
          v-for="(item, index) in planFieldList"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :min-width="item.width"
          :formatter="fieldFormatter"
          show-overflow-tooltip />
        <el-table-column
          v-if="(receivablesPlanUpdate || receivablesPlanDelete || receivablesSaveAuth) && !isSeas"
          :label="$t('crm.components.36e7047148189b68535d374c14bedaf0')"
          fixed="right"
          width="180">
          <template slot-scope="{ row, $index }">
            <el-button
              v-if="receivablesSaveAuth"
              :disabled="!!row.receivablesId"
              type="primary-text"
              style="padding: 0;"
              @click.native="handleFile('createReceivables', row, $index )">
              {{ $t('crm.components.c22b1822e8ec28783d36558f58c4f4e4') }}
            </el-button>
            <el-button
              v-if="receivablesPlanUpdate"
              type="primary-text"
              style="padding: 0;"
              @click.native="handleFile('edit', row, $index )">
              {{ $t('crm.components.8eeb0672621debf13a4656ecfc42c8dd') }}
            </el-button>
            <el-button
              v-if="receivablesPlanDelete"
              type="primary-text"
              style="padding: 0;"
              @click.native="handleFile('delete', row, $index )">
              {{ $t('crm.components.230e566e193491e80e8a87ee26c5471c') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <template v-if="receivablesIndex">
      <div class="rc-head margin-top-base2">
        <el-button
          v-if="!isSeas && receivablesSave"
          icon="el-icon-plus"
          @click="createClick('money')">
          {{ $t('crm.components.c3d857019a09d5501b9a6718d4e098f5') }}
        </el-button>
      </div>
      <el-table
        :data="list"
        :height="tableHeight"
        :cell-class-name="cellClassName"
        stripe
        @row-click="handleRowClick">
        <el-table-column
          v-for="(item, index) in fieldList"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :min-width="item.width"
          show-overflow-tooltip>
          <template slot-scope="{ row, column }">
            <template v-if="item.prop == 'checkStatus'">
              <span
                :style="getStatusStyle(row.checkStatus)"
                class="status-mark" />
              <span>{{ getStatusName(row.checkStatus) }}</span>
            </template>
            <wx-open-data
              v-else-if="item.formType == 'user'"
              :openid="row[column.property]" />
            <template v-else>
              {{ fieldFormatter(row, column) }}
            </template>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <c-r-m-full-screen-detail
      :id="showFullId"
      :visible.sync="showFullDetail"
      :crm-type="showFullCrmType"
      @handle="detailHandle" />

    <c-r-m-all-create
      v-if="isCreate"
      :crm-type="createCrmType"
      :action="createActionInfo"
      @save-success="saveSuccess"
      @close="isCreate=false" />
  </div>
</template>

<script type="text/javascript">
import CRMAllCreate from './CRMAllCreate'
import {
  crmReceivablesPlanDeleteAPI
} from '@/api/crm/receivables'
import { crmReceivablesIndexAPI } from '@/api/crm/receivables.js'
import { crmReceivablesPlanIndexAPI } from '@/api/crm/receivablesPlan.js'

/** 注意  需要删除接口 */
import { objDeepCopy, getWkDateTime } from '@/utils'
import CheckStatusMixin from '@/mixins/CheckStatusMixin'
import { separator } from '@/filters/vueNumeralFilter/filters'
import { getPermissionByKey } from '@/utils'
import moment from 'moment'
import crmTypeModel from '@/views/crm/model/crmTypeModel.js'

export default {
  name: 'RelativeReturnMoney', // 相关回款  可能再很多地方展示 放到客户管理目录下

  components: {
    CRMAllCreate,
    CRMFullScreenDetail: () => import('@/components/CRMFullScreenDetail')
  },

  mixins: [CheckStatusMixin],

  inject: ['rootTabs'],

  props: {
    /** 模块ID */
    id: [String, Number],
    /** 没有值就是全部类型 有值就是当个类型 */
    crmType: {
      type: String,
      default: ''
    },
    /** 是公海 默认是客户 */
    isSeas: {
      type: Boolean,
      default: false
    },
    /** 客户和 合同下 可新建 回款计划 */
    detail: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },

  data() {
    return {
      loading: false,
      list: [],
      fieldList: [],
      tableHeight: '250px',
      showFullDetail: false,
      showFullCrmType: 'receivables',
      showFullId: '', // 查看全屏详情的 ID
      createCrmType: 'receivablesPlan', // 创建回款计划
      isCreate: false, // 新建回款回款
      palnList: [],
      planFieldList: [],
      createActionInfo: {} // 新建回款计划的时候 在客户 合同下导入关联信息
    }
  },

  computed: {
    receivablesPlanIndex() {
      return !!getPermissionByKey('crm.receivablesPlan.index')
    },
    receivablesPlanSave() {
      return !!getPermissionByKey('crm.receivablesPlan.save')
    },
    receivablesPlanUpdate() {
      return !!getPermissionByKey('crm.receivablesPlan.update')
    },
    receivablesPlanDelete() {
      return !!getPermissionByKey('crm.receivablesPlan.delete')
    },
    receivablesIndex() {
      return !!getPermissionByKey('crm.receivables.index')
    },
    receivablesSave() {
      return !!getPermissionByKey('crm.receivables.save')
    },
    receivablesSaveAuth() {
      return !!getPermissionByKey('crm.receivables.save')
    }
  },

  watch: {
    id(val) {
      this.list = []
      this.palnList = []
      this.getList()
      this.getPlanList()
    },

    'rootTabs.currentName'(val) {
      if (val === 'RelativeReturnMoney') {
        this.getList(false)
        this.getPlanList(false)
      }
    }
  },

  mounted() {
    const unit = `（${this.$unit('crm')}）`
    this.planFieldList = [
      { prop: 'num', width: '150', label: this.$t('crm.components.c887c86e8e660a07a417d749efdc06ce') },
      { prop: 'customerName', width: '150', label: this.$t('crm.components.e534d842df74ebd735d2f1b0365737bf') },
      { prop: 'contractNum', width: '150', label: this.$t('crm.components.873d9025e6e93d3d9757da30901aa4d5') },
      { prop: 'money', width: '200', label: '计划回款金额' + unit },
      { prop: 'returnDate', width: '150', label: this.$t('crm.components.b6fdfcd9db8436f75c0e5f4ea027b3b4') },
      { prop: 'returnType', width: '150', label: this.$t('crm.components.a7250011a6b16c4a5d91e64bfc0d8318') },
      { prop: 'remind', width: '150', label: this.$t('crm.components.fdfc8c06c729dc35621169006e94fa16') },
      { prop: 'remark', width: '150', label: this.$t('crm.components.36a3cb02da10c5e98e569f1684237946') }
    ]

    this.getPlanList()

    this.fieldList = [
      { prop: 'number', width: '150', label: this.$t('crm.components.24acdf020b1abcaa57385de75acb9b70') },
      { prop: 'contractNum', width: '150', label: this.$t('crm.components.873d9025e6e93d3d9757da30901aa4d5') },
      { prop: 'contractMoney', width: '150', label: '合同金额' + unit },
      { prop: 'money', width: '150', label: '回款金额' + unit },
      { prop: 'planNum', width: '80', label: this.$t('crm.components.e79bb575724b3bc336eb3a5f72f4c1e3') },
      { prop: 'ownerUserName', width: '100', label: this.$t('crm.components.58decb98b9216643fd7265dc736c06f6'), formType: 'user' },
      { prop: 'checkStatus', width: '100', label: this.$t('crm.components.e7dadc416b4a7afe590bd16f0aa28751') },
      { prop: 'returnTime', width: '150', label: this.$t('crm.components.18c8de972549b922212663c3af5d3faa') }
    ]
    this.getList()
  },

  methods: {
    /**
     * 回款计划列表
     */
    getPlanList(loading = true) {
      this.loading = loading

      const params = {
        pageType: 0,
        type: crmTypeModel[this.crmType],
        searchList: [
          {
            'type': 1,
            'values': [
              this.id
            ],
            'formType': 'text',
            'name': `${this.crmType}_id`
          }
        ]
      }
      crmReceivablesPlanIndexAPI(params)
        .then(res => {
          this.loading = false
          const list = res.data.list || []
          list.forEach(item => {
            item.returnDate = getWkDateTime(item.returnDate)
          })
          this.palnList = list
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 回款列表
     */
    getList(loading = true) {
      this.loading = loading
      const params = {
        pageType: 0,
        type: crmTypeModel[this.crmType],
        searchList: [
          {
            'type': 1,
            'values': [
              this.id
            ],
            'formType': 'text',
            'name': `${this.crmType}_id`
          }
        ]
      }
      crmReceivablesIndexAPI(params)
        .then(res => {
          this.loading = false
          this.list = res.data.list
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 获取上传参数
     */
    getParams() {
      if (this.crmType === 'customer') {
        return { customerId: this.id, pageType: 0 }
      } else if (this.crmType === 'contract') {
        return { contractId: this.id, pageType: 0 }
      }
      return {}
    },

    /**
     * 当某一行被点击时会触发该事件
     */
    handleRowClick(row, column, event) {
      if (column.property == 'number') {
        this.showFullId = row.receivablesId
        this.showFullCrmType = 'receivables'
        this.showFullDetail = true
      }
    },

    /**
     * 当某一行被点击时会触发该事件
     */
    handlePlanRowClick(row, column, event) {
      if (column.property == 'num') {
        this.showFullId = row.receivablesPlanId
        this.showFullCrmType = 'receivablesPlan'
        this.showFullDetail = true
      }
    },

    /**
     * 新建回款和回款计划
     */
    createClick(type) {
      this.createActionInfo = {
        type: 'relative',
        crmType: this.crmType,
        data: {}
      }
      if (type == 'money') {
        if (this.crmType === 'contract') {
          this.createActionInfo.data['customer'] = objDeepCopy(this.detail)
          this.createActionInfo.data['contract'] = objDeepCopy(this.detail)
        } else if (this.crmType === 'customer') {
          this.createActionInfo.data['customer'] = this.detail
        }
        this.createCrmType = 'receivables'
        this.isCreate = true
      } else if (type == 'receivablesPlan') {
        if (this.crmType === 'contract') {
          this.createActionInfo.data['customer'] = objDeepCopy(this.detail)
          this.createActionInfo.data['contract'] = objDeepCopy(this.detail)
        } else if (this.crmType === 'customer') {
          this.createActionInfo.data['customer'] = this.detail
        }
        this.createCrmType = 'receivablesPlan'
        this.isCreate = true
      }
    },

    /**
     * 新建成功
     */
    saveSuccess() {
      if (this.createCrmType == 'receivables') {
        this.$bus.emit('crm-tab-num-update')
        this.getList()
      } else {
        this.getPlanList()
      }
    },

    /**
     * 编辑操作
     */
    handleFile(type, row, index) {
      console.log(type, row, index)
      if (type == 'edit') {
        this.createActionInfo = { type: 'update', id: row.receivablesPlanId, batchId: row.batchId }
        this.createCrmType = 'receivablesPlan'
        this.isCreate = true
      } else if (type == 'delete') {
        this.$confirm(
          this.$t('crm.components.2404665a4772c40b1f75883e90ee1e4e'),
          this.$t('crm.components.4803fe0ef4cd97defce309dad14ba7c4'),
          {
            confirmButtonText: this.$t('crm.components.11ad4a02ee0a39b0ac6a596614326c38'),
            cancelButtonText: this.$t('crm.components.7fd322644ca2f4632945defc4198479b'),
            type: 'warning'
          }
        )
          .then(() => {
            crmReceivablesPlanDeleteAPI([row.receivablesPlanId])
              .then(res => {
                this.palnList.splice(index, 1)
                this.$message.success(this.$t('crm.components.2e90c17455b0aefce48ae96cc518d5c1'))
              })
              .catch(() => {})
          })
          .catch(() => {})
      } else if (type == 'createReceivables') {
        this.createCrmType = 'receivables'
        this.createActionInfo = {
          type: 'relative',
          crmType: this.crmType,
          data: {
            customer: {
              customerName: row.customerName,
              customerId: row.customerId
            },
            contract: {
              contractNum: row.contractNum,
              contractId: row.contractId
            },
            receivablesPlanId: row.receivablesPlanId,
            returnTime: moment().format('YYYY-MM-DD'),
            money: row.money,
            returnType: row.returnType,
            remark: row.remark
          }
        }
        this.isCreate = true
      }
    },

    /**
     * 格式化字段
     */
    fieldFormatter(row, column) {
      // 如果需要格式化
      if (column.property == 'contractMoney' || column.property == 'money') {
        return separator(this.$money('crm', row[column.property] || 0))
      }
      return row[column.property] === '' || row[column.property] === null ? '--' : row[column.property]
    },

    /**
     * @description: 状态颜色
     * @param {*} status
     * @return {*}
     */
    getStatusStyle(status) {
      return {
        backgroundColor: this.getStatusColor(status)
      }
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === 'number') {
        return 'can-visit--underline'
      } else {
        return ''
      }
    },

    /**
     * 通过回调控制class
     */
    planCellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === 'num') {
        return 'can-visit--underline'
      } else {
        return ''
      }
    },

    /**
     * 详情操作
     */
    detailHandle(data) {
      if (data.type === 'delete') {
        this.getList()
        this.$nextTick(() => {
          this.$bus.emit('crm-tab-num-update')
        })
      } else {
        this.getList()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../styles/relativecrm.scss";
@import "../styles/table.scss";
</style>
